
from db.model import Model

def login(db,name,passwd):
    '''
    登陆验证
    :return:
    '''
    where = ['name="%s"'%name,'passwd="%s"'%passwd]
    dic = db.select(where)
    if len(dic) > 0:
        if dic[0]['name'] == name and passwd == dic[0]['passwd']:
            return True
    return False 

def quit():
    '''
    退出系统
    :return:
    '''
    print("|==============系统已退出==============|")

def query(db,name): 
    '''
    查询余额
    :return:
    '''
    where = ['name="%s"'%name]
    ret_dict = db.select(where)
    if len(ret_dict) > 0:
        print('%s,您的余额为：%.2f元' % (name,ret_dict[0]['balance']))
    else:
        print("查询错误")

def charge(db,name):
    '''
    存入
    :return:
    '''
    amount_of_money = input("请输入存款金额：")
    dlist = db.select(['name="%s"'%name])
    if len(dlist) > 0:
        balance = dlist[0]['balance']
        data = {'name':name,'balance':balance+int(amount_of_money)}
        if db.update(data):
            print("存款成功,",end="")
            query(db,name)
    else:
        print("存款流程异常")


def withdraw_money(db,name):
    '''
    取款
    :return:
    '''
    amount_of_money = int(input("请输入取款金额："))
    dlist = db.select(['name="%s"'%name])
    if len(dlist) > 0:
        balance = dlist[0]['balance']
        while int(amount_of_money) > int(balance):
            print("取款金额超过当前余额,请重新输入")
            return
        data = {'name':name,'balance':balance-int(amount_of_money)}
        if db.update(data):
            print("取款成功,",end="")
            query(db,name)

# 系统入口
def run():
    db = Model("bank")
    print("|***************欢迎进入中国银行自助存取款系统***************|")

    while True:
        print("|--------------用户登陆--------------|")
        name = input("请输入用户名：")
        passwd = input("请输入密码：")

        if login(db,name,passwd):
            print("登陆成功")
            print("------1.存款   2.取款   3.余额查询   4.退出------")

            while True:
                cmd = input("请输入指令代码：")
                cmd = int(cmd)
                if cmd == 1:
                    charge(db,name)
                elif cmd == 2:
                    withdraw_money(db,name)
                elif cmd == 3:
                    query(db,name)
                elif cmd == 4:
                    quit()
                    break;
                else:
                    print("输入错误，请重新输入")
            exit()
        else:
            print("登陆失败，请重新登陆")

run()